import React, { useEffect, useState } from 'react'
import axios from "axios";

function Cart() {
  const [cartList, setcartList] = useState([]); //购物车列表数据
  const [allCheck, setAllCheck] = useState(false); //默认为false
  let [totalNum, setTotalNum] = useState(0); //计算总量
  let [totalPrice, setTotalPrice] = useState(0); //计算总价

  // 请求数据 
  useEffect(() => {
    axios.get("/api/cart").then(res => {
      setcartList(res.data);
    })
  }, [])

  // 5.计算总量和总价【reduce】 ---- 计算被选中的商品总量和总价
  const total = () => {
    // 总量 
    totalNum = cartList.reduce((sum, item) => {
      if (item.isCheck) { 
        sum += item.num;
      }

      return sum
    }, 0)
    setTotalNum(totalNum);

    // 总价 
    totalPrice = cartList.reduce((sum, item) => {
      if (item.isCheck) {
        sum += (item.num * item.price)
      }

      return sum;
    }, 0)
    setTotalPrice(totalPrice.toFixed(2))

  }


  // 1.数量增加 
  const addNum = (id) => {
    cartList.forEach(item => {
      if (item.id === id) {
        item.num++;
      }
    })

    setcartList([...cartList])
    total()
  }

  // 2. 数量减少 
  const reduceNum = (id) => {
    cartList.forEach(item => {
      if (item.id === id) {
        item.num--;
      }
    })
    setcartList([...cartList])
    total()

  }

  // 3.全选 
  const onAllCheck = (e) => {
    console.log(e.target.checked);
    setAllCheck(e.target.checked);
    cartList.forEach(item => {
      item.isCheck = e.target.checked
    })

    setcartList([...cartList])
    total()


  }

  // 4.反选 
  const oncheckItem = (id) => {
    cartList.forEach(item => {
      if (item.id === id) {
        item.isCheck = !item.isCheck;
      }
    })
    let all = cartList.every(item => item.isCheck);
    setAllCheck(all);
    setcartList([...cartList]);
    total()

  }


  return (
    <div className='cart'>
      <div className='cartTitle'>
        <input type="checkbox" checked={allCheck} onChange={onAllCheck} />全选
      </div>
      <div className="cartList">
        {
          cartList.length ?
            cartList.map(item => {
              return <li key={item.id}>
                <input type="checkbox" checked={item.isCheck} onChange={() => { oncheckItem(item.id) }} />
                <img src={item.img} alt="" />
                <div>
                  <h4>{item.title}</h4>
                  <p>{item.msg}</p>
                  <p>￥{item.price}元</p>
                </div>
                <div>
                  {/* 减到1，按钮禁用 */}
                  <button disabled={item.num === 1} onClick={() => { reduceNum(item.id) }}>-</button>
                  {item.num}
                  <button onClick={() => { addNum(item.id) }}>+</button>
                </div>

              </li>
            }) : "购物车中还没有商品"
        }

      </div>
      <div className='bottom'>
        <p><input type="checkbox" checked={allCheck} onChange={onAllCheck} />全选</p>
        <div>
          <p>总数:{totalNum}</p>
          <button disabled={totalNum === 0}>结算{totalPrice}</button>
        </div>

      </div>
    </div>
  )
}

export default Cart